﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace TackMessenger
{
    class Connection
    {
        private TcpClient client;
        private TcpListener listener;
        

        Encryption enc;

           
        public Connection(IPAddress address, int port)
        {
            Props.address = address;
            Props.port = port;
            enc = new Encryption();
        }

        
      
        public void listen()
        {
            try
            {
                listener = new TcpListener(Props.address, Props.port);
                listener.Start();

                Byte[] bytes = new Byte[256];
                string data = null;
                NetworkStream stream;

                while (true)
                {
                    client = listener.AcceptTcpClient();

                    data = null;

                    stream = client.GetStream();

                    int i;

                    while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        data = enc.decode(System.Text.Encoding.ASCII.GetString(bytes, 0, i));

                    }

                }
            }
            catch (SocketException e)
            {

                throw e;
            }
            finally
            {
                listener.Stop();
            }




        }

        public bool connect() {
            bool success = true;

            client = new TcpClient();
            try
            {
                client.Connect(Props.address, Props.port);
                Props.connected = true;
            }
            catch (SocketException e)
            {
                Props.connected = false;
                success = false;
                throw e;
            }

            return success;
        }

        public void disconnect()
        {
            if (Props.connected)
            {
                client.Close();
            }

        }


        public bool sendMessage(string message)
        {
            bool success = false;
            if (Props.connected)
            {
                NetworkStream stream;
                Byte[] data = System.Text.Encoding.ASCII.GetBytes(enc.encode(message));

                try
                {
                    stream = client.GetStream();
                    stream.Write(data, 0, data.Length);
                    stream.Close();
                    success = true;
                }
                catch (SocketException e)
                {
                    
                    throw e;
                }
               
            }
            
            return success;
        }
        




    }
}
